<template>
  <base-breadcrumb v-loading="loading">
    <div class="about-master-container">
      <a-card>
        <title-name title="季度考核" />
        <!--        <a-button type="primary" @click="getData">批量编辑</a-button>-->
        <a-form-model>
          <a-row>
            <a-col :span="8">
              <a-form-model-item label="考核时间">
                <span class="requiredFormItem">
                <BSelect v-model="time" :list="dateList" @change2="getData" />
                </span>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="实际考核人员">
                <b-input disabled :value="currentUserName" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>

        <a-table
          :columns="columns"
          :data-source="list"
          :pagination="false"
        >
          <template slot="title1" slot-scope="text,record,index">
            <div style="margin:22px 0;">{{ text }}</div>
          </template>
          <template :slot="item.dataIndex" slot-scope="text,record,index" v-for="item in columns.slice(1) ">
            <span v-if="index === 0">{{ text }}</span>
            <template v-else>
              <span v-if="safeIndex.find(x=>x === item.dataIndex)">{{ record[item.dataIndex]['val'] }}</span>
              <b-input-number v-else :min="0" v-model="record[item.dataIndex]['val']"
                              @blur="calc($event,item.dataIndex,record)"
              />
            </template>
            <div class="file-wrapper" v-show="record[item.dataIndex]['isUpload']">
              <div class="upload" v-if="!record[item.dataIndex]['commonId']"
                   v-loading="record[item.dataIndex]['loading']"
              >
                <div class="notice">请上传不合格佐证附件</div>
                <input type="file" @change="upload($event,item.dataIndex,record)">
              </div>
              <a-popover v-else placement="top">
                <template slot="content">
                  <a
                    :href="'/api/ycloud-file-center/oper/download?access_token=' + token + '&fileId=' + record[item.dataIndex]['file'].fileId"
                    target="_parent"
                  >下载</a>
                  <a-divider type="vertical" />
                  <a @click="$filePreview(record[item.dataIndex]['file'])">查看</a>
                </template>
                <a-button size="small" type="link">
                  {{ record[item.dataIndex]['file'].fileName }}
                </a-button>
                <div class="close-wrapper">
                  <div class="close-wrap" @click="remove(record,item.dataIndex)">
                    <svg t="1649402032590" class="icon" viewBox="0 0 1024 1024" version="1.1"
                         xmlns="http://www.w3.org/2000/svg"
                         p-id="2351"
                    >
                      <path
                        d="M176.661601 817.172881C168.472798 825.644055 168.701706 839.149636 177.172881 847.338438 185.644056 855.527241 199.149636 855.298332 207.338438 846.827157L826.005105 206.827157C834.193907 198.355983 833.964998 184.850403 825.493824 176.661601 817.02265 168.472798 803.517069 168.701706 795.328267 177.172881L176.661601 817.172881Z"
                        p-id="2352" fill="#d8061c"
                      ></path>
                      <path
                        d="M795.328267 846.827157C803.517069 855.298332 817.02265 855.527241 825.493824 847.338438 833.964998 839.149636 834.193907 825.644055 826.005105 817.172881L207.338438 177.172881C199.149636 168.701706 185.644056 168.472798 177.172881 176.661601 168.701706 184.850403 168.472798 198.355983 176.661601 206.827157L795.328267 846.827157Z"
                        p-id="2353" fill="#d8061c"
                      ></path>
                    </svg>
                  </div>
                </div>
              </a-popover>
            </div>
          </template>
        </a-table>
      </a-card>
      <div class="pub-header-btn page-btn-right-top">
        <a-button @click="submit" type="primary" v-if="originList.length">提交</a-button>
        <a-button @click="$close">返回</a-button>
      </div>
    </div>
  </base-breadcrumb>
</template>
<script>
import {
  assessmentBatchDetails,
  batchHeader,
  batchList,
  querySafeTyScore
} from '@/api/subcontractors/quarterAssessment'
import moment from 'moment'
import { uploadFile, uploadFile2 } from '@/api'
import Vue from 'vue'

export default {
  name: 'batchEditAssessment',
  components: {},
  data() {
    return {
      loading: false,
      time: '',
      token: '',
      slotList: [],
      columns: [],
      list: [],
      columns2: [
        {
          'dataIndex': '1',
          'formId': null,
          'title': '管理人员配置(10)',
          'code': null,
          'sort': null,
          'inputType': null
        },
        {
          'dataIndex': '2',
          'formId': null,
          'title': '劳动力(10)',
          'code': null,
          'sort': null,
          'inputType': null
        },
        {
          'dataIndex': '3',
          'formId': null,
          'title': '方案执行(10)',
          'code': null,
          'sort': null,
          'inputType': null
        },
        {
          'dataIndex': '4',
          'formId': null,
          'title': '施工工期(10)',
          'code': null,
          'sort': null,
          'inputType': null
        },
        {
          'dataIndex': '5',
          'formId': null,
          'title': '施工质量(10)',
          'code': null,
          'sort': null,
          'inputType': null
        },
        {
          'dataIndex': '6',
          'formId': null,
          'title': '安全生产(10)',
          'code': null,
          'sort': null,
          'inputType': null
        },
        {
          'dataIndex': '7',
          'formId': null,
          'title': '文明施工管理(5)',
          'code': null,
          'sort': null,
          'inputType': null
        },
        {
          'dataIndex': '8',
          'formId': null,
          'title': '环境行为(5)',
          'code': null,
          'sort': null,
          'inputType': null
        },
        {
          'dataIndex': '9',
          'formId': null,
          'title': '物资设备管理(5)',
          'code': null,
          'sort': null,
          'inputType': null
        },
        {
          'dataIndex': '10',
          'formId': null,
          'title': '商务管理(10)',
          'code': null,
          'sort': null,
          'inputType': null
        },
        {
          'dataIndex': '11',
          'formId': null,
          'title': '劳动合同(5)',
          'code': null,
          'sort': null,
          'inputType': null
        },
        {
          'dataIndex': '12',
          'formId': null,
          'title': '民工工资支付(5)',
          'code': null,
          'sort': null,
          'inputType': null
        },
        {
          'dataIndex': '13',
          'formId': null,
          'title': '诚信建设(5)',
          'code': null,
          'sort': null,
          'inputType': null
        }
      ],
      list2: [{
        '1': '无管理人员花名册的扣1分，管理人员上岗证不全的扣1-3分，队伍管理机构设置不全的扣3-5分，管理水平或施工生产能力不能满足施工需要的扣3-5分；项目部管理人员没有按照投标承诺配置的扣5分。',
        '2': '未按投标承诺提供现场劳动力数量的扣5-10分；现场劳动力不满足现场施工需要的扣10分；未提供技术工人花名册的扣1-3分；技术工人持证率达不到60%的扣3-5分。',
        '3': '每发现一处未执行施工方案、技术交底扣3-5分；每发现一处未按照施工图、图纸会审、设计变更施工扣5-7分；因上述原因造成返工扣10分。',
        '4': '月施工工期比计划工期每拖延1天扣1分；未实现合同（计划）工期节点扣10分。',
        '5': '每发生一次检验批验收质量不符合国家质量验收标准的扣1分；分项工程未一次验收合格的扣5分；未达到合同质量要求的扣10分；因质量问题影响分部、竣工验收扣10分。',
        '6': '未按合同要求配备安全管理人员扣10分；未按合同要求配备安全器具扣10分；周安全检查得分少于90分的扣3分；存在安全隐患且未认真整改的扣5分；发生安全事故的扣5-10分。',
        '7': '现场文明施工效果较差扣1-3分；未达到约定的创建市级（省级）文明工地的扣5分，未达到合同规定的安全要求扣5分。',
        '8': '施工现场防尘、防噪、防毒、防污染不符合要求的扣1-3分，工人生活区（食堂）卫生不整洁的扣1-3分，生活垃圾处理不及时（或不符合有关规定）的扣2-4分；每发生一次因环境、卫生问题被行政部门通报处罚扣5分；不符合合同规定环境要求扣5分。',
        '9': '现场未工完料清扣2分，成品保护不到位扣2分，材料堆放不整齐扣2分；每发现一处材料浪费扣2分；每发现一次材料偷盗现象扣5分；每发现一次进场物资不合格现象扣5分；每发现一次不按规定操作设备扣2分；安全使用整改不及时每次扣5分。',
        '10': '每发生一次不及时办理签证月清月结扣5分；分包结算办理不及时、不配合扣5分；每发生一次虚报签证扣5分；每发生一次恶意索赔扣10分。',
        '11': '没有与工人签订劳动合同的扣5分；劳动合同签订不全的扣1-3分；劳动合同签字盖章手续不全的扣1-3分；劳动合同签订不真实扣1-3分。',
        '12': '未能执行分账支付的扣5分；未能按期提供工人出勤表和《工人劳动工资发放记录表》扣2分；所提供的工人出勤表和《工人劳动工资发放记录表》不符合手册要求扣2分。',
        '13': '未能提供合法经营的有关资料（如：营业执照、资质证书、安全生产许可证、企业代码、税务登记证、进驻工程所在地的施工许可备案登记等资料）的扣5分；提供不全或有效性不够的扣1-3分；员工发生不遵纪守法行为的扣3-5分；不能有效配合现场施工的扣3-5分，不能有效配合人员管理的扣3-5分。'
      }],
      originList: [],
      safeIndex: [],
      dateList: [],
      currentUserName: '',
      projectName: ''
    }
  },
  computed: {},
  watch: {},
  created() {
    this.token = Vue.getAcloudProvider().getAccessToken()
    // this.time = this.$dateFormat(Date.now(), 'D')
    this.projectName = this.$route.query.projectName
    this.currentUserName = this.$userInfo().name


    let temp = []
    let currentYear = (new Date()).getFullYear()
    let curryMonth = (new Date()).getMonth()
    // let currentQuarter = ((new Date()).getMonth() + 1) % 3
    let currentQuarter = curryMonth? Math.floor(curryMonth/3):0;
    let rela = { 1: '一', 2: '二', 3: '三', 4: '四' }
    this.time = `${currentYear}年第${rela[currentQuarter + 1]}季度`
    Array.from({ length: ((currentYear - 2000) * 4 + currentQuarter + 1) }).map((v, i) => {
      let year = parseInt(i / 4)
      let quarter = i % 4

      if (year < 10) year = '0' + year
      let name = `20${year}年第${rela[quarter + 1]}季度`
      temp.push({ id: name, name, i })
    })
    temp.sort((a, b) => b.i - a.i)
    this.dateList = temp

    this.getData()

  },
  methods: {
    async getData() {
      console.log('getDate')
      if (!this.time) return
      this.loading = true
      let safeScore = []
      this.originList = []
      this.safeIndex = []
      this.list = []
      this.columns = []
      // if (false) {
      if (true) {
        // let date = this.$dateFormat(moment(this.time), 'M')
        let date = this.time
        // date = '2022-02'
        const res2 = await batchList({ assessmentTime: date })
        if (res2.code === 200) {
          if (res2.data.length) {
            this.originList = res2.data.filter(v => {
              return v['map'] && Object.keys(v['map']).length
            })
            let idList = this.originList.map(v => v.id)
            let r3 = await querySafeTyScore({ idList, assessmentTime: date })
            if (r3.code === 200) {
              safeScore = r3.data
            }
          }
        }
      } else {
        this.originList = []
        safeScore = []
      }

      if (this.originList.length) {
        // const res = await batchHeader({ id: this.$route.query.id })
        const res = await batchHeader({ id: this.originList[0].id })
        if (res.code === 200) {
          res.data.assessmentFormHeaderResults.map(v => {
            v.scopedSlots = { customRender: v.dataIndex }
            v.width = (100 / (res.data.assessmentFormHeaderResults.length + 1)) + '%'
            if (v.code === 'AQZJ') {
              this.safeIndex.push(v.dataIndex)
            }
          })
          this.columns = [{
            'dataIndex': 'title',
            scopedSlots: { customRender: 'title1' },
            'formId': null,
            'title': '考核名称及考核评分',
            'code': null,
            'sort': null,
            'inputType': null,
            width: (100 / (res.data.assessmentFormHeaderResults.length + 1)) + '%'
            // fixed: 'left'
          }].concat(res.data.assessmentFormHeaderResults)
          console.log('columns', this.columns)
          this.list = [{ title: '扣分标准', ...res.data.indexHeader }]
        }
      } else {
        this.$noticeError('当前季度没有考核内容')
      }

      console.log('safeIndex', this.safeIndex)
      console.log('safeScore', safeScore)
      console.log('originList', this.originList)
      // this.safeIndex = ['3', '4']

      this.originList.map(v => {
        if (Object.keys(v['map']).length > 0) {
          let has = safeScore.find(w => w.subContractorId === v.subContractorId)
          if (has) {
            this.safeIndex.map(w => {
              v['map'][w]['safeScore'] = has.score
            })
          } else {
            this.safeIndex.map(w => {
              v['map'][w]['safeScore'] = ''
            })
          }
        }
      })

      let list = this.originList.map(v => {
        let keys = Object.keys(v.map)
        let r = { title: v.subContractorName }
        keys.map(w => {
          if (this.safeIndex.find(x => x === w)) {
            let currentColumns = this.columns.find(v => v.dataIndex === w)
            if (currentColumns) {
              try {
                if (v.map[w].safeScore !== '') {
                  v.map[w].safeScore = Math.round((Number(currentColumns.sort) / 100) * v.map[w].safeScore)
                }
              } catch (e) {
              }
              r[w] = { val: v.map[w].safeScore, commonId: '', isUpload: false, isSafe: true, loading: false, file: {} }
            } else {
              r[w] = { val: v.map[w].safeScore, commonId: '', isUpload: false, isSafe: true, loading: false, file: {} }
            }
          } else {
            r[w] = { val: '', commonId: '', isUpload: false, isSafe: false, loading: false, file: {} }
          }
        })
        return r
      })
      console.log('list', list)

      this.list = this.list.concat(list)
      this.loading = false
    },
    async upload(e, type, row) {
      let file = e.target.files[0]
      let re = new RegExp('[\u4E00-\\u9FFF]+', 'g')
      if (!re.test(file.name)) {
        this.$confirm({
          title: '提示',
          content: this.errorTips ? this.errorTips : '请规范附件名称，附件名称中需含有汉字',
          okType: 'danger'
        })
        return false
      }
      const data = new FormData()
      data.append('file', file)
      data.append('businessCode', 'LCM08')

      row[type].loading = true
      let res = await uploadFile2(data)
      row[type].loading = false
      if (res.code === 200) {
        let datas = res.data
        datas.name = datas.fileName + datas.suffixName
        datas.url = '/api/ycloud-file-center/oper/download?access_token=' + this.token + '&fileId=' + datas.fileId
        datas.uid = datas.id
        row[type]['file'] = datas
        row[type]['commonId'] = datas.commonId
      }
      this.loading = false
    },
    calc(e, type, row) {
      if (e.target.value) {
        row[type].val = Math.round(Number(e.target.value))
        let res = this.columns.find(v => v.dataIndex == type)
        console.log('res', res)
        if (res.sort) {
          if (row[type].val > Number(res.sort)) {
            return row[type]['val'] = res.sort
          }
          if (row[type].val < (Number(res.sort) * 0.6)) {
            // this.$noticeWarning('低于60%')
            row[type]['isUpload'] = true
          } else {
            row[type]['isUpload'] = false
          }
        }
      }
    },
    remove(row, type) {
      this.$submitConfirm(() => {
        row[type]['file'] = {}
        row[type]['commonId'] = ''
      }, '请确认是否要删除已上传附件？')
    },
    async submit() {
      let data = []
      let res = false
      let res2 = false
      let res4 = false
      try {
        //从第二行开始
        this.list.slice(1).map(v => {
          let keys = Object.keys(v)
          console.log('keys', keys)

          let noTitleKeys = keys.filter(v => v !== 'title')
          console.log('noTitleKeys', noTitleKeys)
          if (noTitleKeys.length === this.columns.length) {
            noTitleKeys.pop()
          }
          noTitleKeys.map(w => {
            if (!v[w]['isSafe']) {
              if (v[w].val === '' || v[w].val === null) {
                res = true
              }
              let res3 = this.columns.find(j => j.dataIndex == w)
              console.log('res3', res3)
              if (res3.sort) {
                if (Number(v[w].val) < (Number(res3.sort) * 0.6)) {
                  if (v[w].commonId === '') {
                    res2 = true
                  }
                }
              }
            } else {
              if (v[w].val === '' || v[w].val === null) {
                res4 = true
              }
            }
          })
        })
        if (res) return this.$noticeWarning('请填写完整数据')
        if (res2) return this.$noticeWarning('单项分数低于指标分值60%的，必须上传佐证附件')
        if (res4) return this.$noticeWarning('安监季度考核本月无考核分数，请先联系相关人员进行安监季度考核')

        // return
        let copyList = JSON.parse(JSON.stringify(this.originList))
        this.list.map(v => {
          if (v.title !== '扣分标准') {
            let keys = Object.keys(v).filter(w => w !== 'title')
            let row = copyList.find(j => j.subContractorName == v.title)
            let obj = {
              id: row.id,
              contentList: []
            }
            if (row.map) {
              keys.map(w => {
                let mapRow = row.map[w]
                let mapRowKeys = Object.keys(mapRow)
                mapRowKeys.map(x => {
                  if (mapRow[x] === '实际考核人员') {
                    mapRow[x] = this.currentUserName
                  }
                  if (mapRow[x] === '实际评分') {
                    mapRow[x] = v[w].val
                  }
                  if (mapRow[x] === '状态') {
                    mapRow[x] = '已评分'
                  }
                })
                mapRow.commonId = v[w].commonId
                delete mapRow.safeScore

                obj.contentList.push(mapRow)
              })
            }
            data.push(obj)
          }
        })
      } catch (error) {
        console.log(error)
        return this.$noticeWarning('数据格式出现错误，请联系管理员')
      }
      this.$console(data)

      this.$submitConfirm(async () => {
        this.loading = true
        let res4 = await assessmentBatchDetails(data)
        this.loading = false
        if (res4.code === 200) {
          this.$noticeSuccess('提交成功')
          this.$close()
        }
      }, '请确认是否要提交，提交后不可修改？')
    }
  }
}
</script>
<style scoped lang="less">
.file-wrapper {
  margin-top: .5rem;
  position: relative;

  .notice {
    color: #00b0f0;
  }

  input {
    position: absolute;
    top: 0;
    opacity: 0;
  }
}

.close-wrapper {
  display: inline-block;
}

.close-wrap {
  width: 16px;
  height: 16px;
  padding: 3px;
  background: rgb(255, 190, 190);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

</style>
